//
//  CertificatePhotosViewController.m
//  MagicZhao
//
//  Created by hy002 on 2017/12/6.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "CertificatePhotosViewController.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "cerImageModel.h"

static NSString *cellPath = @"certifCell";
@interface CertificatePhotosViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSMutableArray *imgArray;
@property (nonatomic, strong)NSMutableArray *imgUrlArray;

@end

@implementation CertificatePhotosViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _imgArray = [NSMutableArray array];
    _imgUrlArray = [NSMutableArray array];
    if (_preImagesArr.count > 0 && _preImagesArr) {
        for (int i = 0; i < _preImagesArr.count; i++) {
            cerImageModel *cerModel = _preImagesArr[i];
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:cerModel.url]];
            UIImage *image = [UIImage imageWithData:data];
            [_imgArray addObject:image];
            [_imgUrlArray addObject:cerModel.url];
        }
    }
    [self creatUI];
}

- (void)creatUI
{
    self.navigationItem.title = @"证书";
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.translucent = NO;
    UIButton *rightBtn = [ZCControl createButtonWithFrame:CGRectMake(0, 0, 40, 30) ImageName:nil Target:self Action:@selector(saveAction) Title:@"保存" Font:16.0];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIBarButtonItem *barbtn = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = barbtn;
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.backgroundColor = BacksColor;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _imgArray.count+1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5*displaywidth)];
    lineView.backgroundColor = BacksColor;
    [cell.contentView addSubview:lineView];
    if (indexPath.row == _imgArray.count)
    {
        UIView *addView = [[UIView alloc] initWithFrame:CGRectMake(60*displaywidth, 30*displaywidth, SCREEN_WIDTH-120*displaywidth, 110*displaywidth)];
        addView.backgroundColor = [UIColor whiteColor];
        addView.layer.cornerRadius = 10;
        addView.layer.masksToBounds = YES;
        addView.layer.borderColor = RGB(204, 204, 204).CGColor;
        addView.layer.borderWidth = 1;
        [cell.contentView addSubview:addView];
        CGFloat W = SCREEN_WIDTH-120*displaywidth;
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(W/2-12.5*displaywidth, 25*displaywidth, 25*displaywidth, 20*displaywidth) ImageName:@"tianjia-"];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        [addView addSubview:imgView];
        UILabel *tostLab = [ZCControl createLabelWithFrame:CGRectMake(20*displaywidth, 60*displaywidth, W-40*displaywidth, 30*displaywidth) Font:14.0 Text:@"证书照片" Color:RGB(179, 179, 179)];
        tostLab.textAlignment = NSTextAlignmentCenter;
        [addView addSubview:tostLab];
    }
    else
    {
        UIImageView *bigImgView = [ZCControl createImageViewWithFrame:CGRectMake(0, 5*displaywidth, SCREEN_WIDTH, 200*displaywidth) ImageName:nil];
        bigImgView.image = _imgArray[indexPath.row];
        bigImgView.contentMode = UIViewContentModeScaleAspectFill;
        bigImgView.layer.masksToBounds = YES;
        [cell.contentView addSubview:bigImgView];
        UIButton *deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(bigImgView.frame.size.width - 20, 0, 20, 20)];
        deleteBtn.backgroundColor = [UIColor clearColor];
        [deleteBtn addTarget:self action:@selector(onClickDeleteBtn:) forControlEvents:UIControlEventTouchUpInside];
        [deleteBtn setImage:[UIImage imageNamed:@"shanchu"] forState:UIControlStateNormal];
        deleteBtn.tag = indexPath.row;
        [bigImgView addSubview:deleteBtn];
    }
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == _imgArray.count)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        //拍照
        [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            HYLog(@"拍照");
            [self takePhoto];
            
        }]];
        
        //从相册中选取
        [alertVC addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            HYLog(@"从相册中选取");
            [self choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypePhotoLibrary];
            
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            HYLog(@"取消");
            [self dismissViewControllerAnimated:NO completion:nil];
        }]];
        
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    else
    {
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == _imgArray.count)
    {
        return 165*displaywidth;
    }
    return 205*displaywidth;
}

- (void)onClickDeleteBtn:(UIButton *)sender {
    [_imgArray removeObjectAtIndex:sender.tag];
    [_imgUrlArray removeObjectAtIndex:sender.tag];
    [_tableview reloadData];
}

-(void)takePhoto
{
    //    判断是否打开相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您尚未开启相机权限，请去系统设置界面打开相机权限！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
        
        
    }
    else
    {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            //            设置拍照后的图片可被编辑
            picker.allowsEditing = YES;
            picker.sourceType = sourceType;
            
            [self presentViewController:picker animated:YES completion:nil];
        }else
        {
            
        }
        
    }
}

-(void)choseImageWithTypeCameraTypePhotoLibrary:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = type;
    imagePicker.allowsEditing = YES;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImageOrientation imageOrientation = image.imageOrientation;
        if(imageOrientation!=UIImageOrientationUp)
        {
            UIGraphicsBeginImageContext(image.size);
            [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        
    }
    [_imgArray addObject:image];
    
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HttpTool uploadImageWithPath:SERVER_fileUpload params:nil thumbName:@"file" image:image success:^(id json)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([json server_Getcodecheck])
         {
             NSArray *urlAry = json[@"data"];
             if (urlAry.count > 0)
             {
                 NSString *imgurl = urlAry[0];
                 if (imgurl.length > 0)
                 {
                     [weakSelf.imgUrlArray addObject:imgurl];
                 }
                 
             }
         }
         else
         {
             
         }
         
     } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     } progress:^(CGFloat progress) {
         
     }];
    
    
    [picker dismissViewControllerAnimated:YES completion:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableview reloadData];
        });
    }];
}
- (void)saveAction
{
    if (_imgUrlArray.count == 0)
    {
        [LTools showMBProgressWithText:@"请添加照片" addToView:self.view];
        return;
    }
    NSMutableArray *cerImgAry = [NSMutableArray arrayWithCapacity:0];
    for (NSString *imgUrl in _imgUrlArray)
    {
        NSDictionary *urlDic = @{@"url":imgUrl};
        [cerImgAry addObject:urlDic];
    }
    WEAKSELF;
    NSDictionary *dic = @{@"certificateImgs":cerImgAry};
    [HYBaseHandler requestUpdateWorkerInfoParmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            [LTools showMBProgressWithText:@"保存成功" addToView:sharedDelegate.window];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
